package bservice

import (
    "errors"
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "gonaio_base/function"
)

type JWT struct {
    key        string
    expireTime int64
}

var jwtInstance = new(JWT)

func (Service) GetJWT() *JWT {
    return jwtInstance
}

/*
   key 生成token约定的key
   expireTime 生成的token多长时间失效，单位秒
*/
func (that *JWT) SetConfig(key string, expireTime int64) *JWT {
    that.key = key
    that.expireTime = expireTime
    return that
}

func (that JWT) getKey() []byte {
    return []byte(that.key)
}

func (that JWT) GetToken(data jwt.MapClaims) (token string) {
    data["jwtExpireTime"] = bfunction.GetTimestamp() + that.expireTime
    t := jwt.NewWithClaims(jwt.SigningMethodHS256, data)
    token, _ = t.SignedString(that.getKey())
    return
}

func (that JWT) Parse(data string) (result jwt.MapClaims, err error) {
    token, err := jwt.Parse(data, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("%v", token.Header["alg"])
        }
        return that.getKey(), nil
    })
    if err != nil {
        return
    }
    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
        if claims["jwtExpireTime"].(float64) > float64(bfunction.GetTimestamp()) {
            result = claims
        } else {
            return result, errors.New("jwtExpireTime error")
        }
    }
    return
}
